package com.jsbs.iam.user.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.jsbs.iam.common.core.dto.Result;
import com.jsbs.iam.common.core.utils.Json;
import com.jsbs.iam.common.core.utils.StringUtils;
import com.jsbs.iam.user.constant.Constants;
import com.jsbs.iam.user.dto.ApplyTypeAddDto;
import com.jsbs.iam.user.dto.ApplyTypeDeleteDto;
import com.jsbs.iam.user.dto.ApplyTypeSelectDto;
import com.jsbs.iam.user.service.ApplyTypeService;
import com.jsbs.iam.user.vo.ApplyTypeDetailVo;
import com.jsbs.iam.user.vo.RelevancyApplyVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @BelongsProject: iam
 * @BelongsPackage: com.jsbs.iam.user.controller
 * @Author: WangJiYuan
 * @Description: 应用中心  应用类型
 * @Version: 2023-01-03  14:01
 */
@Slf4j
@RestController
@RequestMapping("/iam/user/applyType")
public class ApplyTypeController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ApplyTypeController.class);

    @Autowired
    private ApplyTypeService applyTypeService;

    private static final String ADMIN_USER = "admin";
    /**
     * 获取关联应用
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/getRelevancyApply")
    public Result getRelevancyApply(HttpServletRequest httpServletRequest) {
        logger.info("Route=>ApplyTypeController method=>getRelevancyApply 获取关联应用");
        try {
            // todo  wjy  临时获取companyCode方法
            String companyCode = httpServletRequest.getHeader(Constants.COMPANY_CODE);
            companyCode = "000001";
            if (StringUtils.isEmpty(companyCode)) {
                log.warn("Route=>ApplyTypeController method=>getRelevancyApply 获取关联应用，当前登录人归属租户信息异常");
                return Result.failWithMsg("登录人归属租户信息异常");
            }
            //获取关联应用
            List<RelevancyApplyVo> info = applyTypeService.getRelevancyApply(companyCode);
            logger.info("Route=>ApplyTypeController method=>getRelevancyApply 获取关联应用>>成功，出参：{}", JSON.toJSONString(info));
            return new Result(Result.SUCCESS, "获取关联应用成功", info);
        } catch (Exception e) {
            logger.error("Route==>ApplyTypeController method=>getRelevancyApply 获取关联应用异常，入参：{}，异常：{}", "", e);
            return handleException(e);
        }
    }

    /**
     * 新增应用类型
     * @param applyTypeAddDto
     * @return
     */
    @PostMapping("/insetApplyTypeInfo")
    public Result insetApplyTypeInfo(HttpServletRequest httpServletRequest,@RequestBody ApplyTypeAddDto applyTypeAddDto) {
        logger.info("Route==>ApplyTypeController method=insetApplyTypeInfo 新增应用类型，入参：{}", JSON.toJSONString(applyTypeAddDto));
        try {
            // todo  wjy  临时获取companyCode和userCode方法
            String companyCode = httpServletRequest.getHeader(Constants.COMPANY_CODE);
            //String userCode = httpServletRequest.getHeader(Constants.USER_CODE);
            String userName = httpServletRequest.getHeader(Constants.NAME);
            companyCode = "000001";
            //userCode = "001001";
            userName = "wjy";

            if (StringUtils.isEmpty(companyCode)) {
                log.warn("Route=>ApplyTypeController method=>insetApplyTypeInfo 新增应用类型，当前登录人归属租户信息异常");
                return Result.failWithMsg("登录人归属租户信息异常");
            }
            /*if (StringUtils.isEmpty(userCode)) {
                log.warn("Route=>ApplyTypeController method=>insetApplyTypeInfo 新增应用类型，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }*/
            if (StringUtils.isEmpty(userName)) {
                log.warn("Route=>ApplyTypeController method=>insetApplyTypeInfo 新增应用类型，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }
            applyTypeAddDto.setCompanyCode(companyCode);
            applyTypeAddDto.setCreatePerson(userName);

            if (StringUtils.isNull(applyTypeAddDto.getApplyTypeName())) {
                logger.info("新增应用类型失败{}", JSON.toJSONString(applyTypeAddDto));
                return Result.failWithMsg("应用类型名称为空");
            }else {
                //校验应用类型名称唯一
                int count = applyTypeService.verifyApplyTypeName(applyTypeAddDto.getApplyTypeName(),companyCode);
                if (count > 0) {
                    logger.info("新增应用类型失败{}", JSON.toJSONString(applyTypeAddDto));
                    return Result.failWithMsg("应用类型名称不唯一");
                }
            }
            if (StringUtils.isNull(applyTypeAddDto.getApplyUrl())) {
                logger.info("新增应用类型失败{}", JSON.toJSONString(applyTypeAddDto));
                return Result.failWithMsg("应用类型前端链接为空");
            }
            if (StringUtils.isNull(applyTypeAddDto.getOrgType())) {
                logger.info("新增应用类型失败{}", JSON.toJSONString(applyTypeAddDto));
                return Result.failWithMsg("组织类型编码为空");
            }
            if (CollectionUtils.isEmpty(applyTypeAddDto.getOrgCodes())) {
                logger.info("新增应用类型失败{}", JSON.toJSONString(applyTypeAddDto));
                return Result.failWithMsg("组织编码为空");
            } else {
                //根据组织编码查询组织类型
                List<String> orgTypes = applyTypeService.verifyOrgType(applyTypeAddDto.getOrgCodes(), companyCode);
                if (CollectionUtils.isEmpty(orgTypes)) {
                    logger.info("新增应用类型失败{}", JSON.toJSONString(applyTypeAddDto));
                    return Result.failWithMsg("所选组织不是本系统组织类型下的组织");
                } else if (orgTypes.size() != 1) {//校验组织是否隶属于多个组织类型下的组织
                    logger.info("新增应用类型失败{}", JSON.toJSONString(applyTypeAddDto));
                    return Result.failWithMsg("所选组织隶属于多个组织类型下的组织");
                }
            }
            //校验关联应用
            if (CollectionUtils.isNotEmpty(applyTypeAddDto.getApplyCodes())) {
                //校验所关联的应用是否关联其他应用类型
                int flagSum = applyTypeService.verifyRelevancyApply(applyTypeAddDto.getApplyCodes(), applyTypeAddDto.getApplyTypeCode(),companyCode);
                if (flagSum != 0) {
                    logger.info("修改应用类型数据失败{}", JSON.toJSONString(applyTypeAddDto));
                    return Result.failWithMsg("关联应用系统已关联其他应用类型, 请重新选择 !");
                }
            }
            //新增应用类型
            applyTypeService.insetApplyTypeInfo(applyTypeAddDto);
            logger.info("Route=>ApplyTypeController method=>insetApplyTypeInfo 新增应用类型>>成功，出参：{}", "");
            return Result.successWithMsg("新增应用类型成功");
        } catch (Exception e) {
            logger.error("Route==>ApplyTypeController method=>insetApplyTypeInfo 新增应用类型异常，入参：{}，异常：{}", JSON.toJSONString(applyTypeAddDto), e);
            return handleException(e);
        }
    }

    /**
     * 查询应用类型数据
     * @param applyTypeSelectDto
     * @return
     */
    @PostMapping("/getApplyTypeInfo")
    public Result getApplyTypeInfo(HttpServletRequest httpServletRequest,@RequestBody ApplyTypeSelectDto applyTypeSelectDto) {
        logger.info("Route==>ApplyTypeController method=getApplyTypeInfo 查询应用类型数据，入参：{}", JSON.toJSONString(applyTypeSelectDto));
        try {
            // todo  wjy  临时获取companyCode方法
            String companyCode = httpServletRequest.getHeader(Constants.COMPANY_CODE);
            String userCode = httpServletRequest.getHeader(Constants.USER_CODE);
            String adminRoleCode = httpServletRequest.getHeader(Constants.ADMIN_ROLE_CODE);
            companyCode = "000001";
            userCode = "admin";
            adminRoleCode = "JS0030";
            if (StringUtils.isEmpty(companyCode)) {
                logger.warn("Route=>ApplyTypeController method=>getApplyTypeInfo 查询应用类型数据，当前登录人归属租户信息异常");
                return Result.failWithMsg("登录人归属租户信息异常");
            }
            if (StringUtils.isEmpty(userCode)) {
                logger.warn("Route=>ApplyTypeController method=>getApplyTypeInfo 查询应用类型数据，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }
            if (!ADMIN_USER.equals(userCode) && StringUtils.isEmpty(adminRoleCode)) {
                logger.warn("Route=>ApplyTypeController method=>getApplyTypeInfo 查询应用类型数据，当前登录人角色信息异常");
                return Result.failWithMsg("登录人角色信息异常");
            }
            applyTypeSelectDto.setCompanyCode(companyCode);
            applyTypeSelectDto.setCreatePerson(userCode);
            applyTypeSelectDto.setAdminRoleCode(adminRoleCode);

            if (StringUtils.isNotNull(applyTypeSelectDto.getApplyTypeCode())) {
                if (applyTypeSelectDto.getApplyTypeCode().length() > 20) {
                    logger.info("查询应用类型数据失败{}", JSON.toJSONString(applyTypeSelectDto));
                    return Result.failWithMsg("应用类型编码输入不能超20");
                }
            }
            if (StringUtils.isNotNull(applyTypeSelectDto.getApplyTypeName())) {
                if (applyTypeSelectDto.getApplyTypeName().length() > 20) {
                    logger.info("查询应用类型数据失败{}", JSON.toJSONString(applyTypeSelectDto));
                    return Result.failWithMsg("应用类型名称输入不能超20");
                }
            }
            if (StringUtils.isNotNull(applyTypeSelectDto.getApplyName())) {
                if (applyTypeSelectDto.getApplyName().length() > 20) {
                    logger.info("查询应用类型数据失败{}", JSON.toJSONString(applyTypeSelectDto));
                    return Result.failWithMsg("应用名称输入不能超20");
                }
            }
            //查询应用类型数据
            PageInfo pageInfo = applyTypeService.getApplyTypeInfo(applyTypeSelectDto);
            logger.info("Route==>ApplyTypeController method=getApplyTypeInfo 查询应用类型数据>>成功，出参：{}", JSON.toJSONString(pageInfo));
            return new Result(Result.SUCCESS, "查询应用类型数据成功", pageInfo);
        } catch (Exception e) {
            logger.error("Route==>ApplyTypeController method=>getApplyTypeInfo 查询应用类型数据异常，入参：{}，异常：{}", JSON.toJSONString(applyTypeSelectDto), e);
            return handleException(e);
        }
    }

    /**
     * 根据应用类型编码查询应用类型详细数据
     * @param applyTypeCode
     * @return
     */
    @PostMapping("/getApplyTypeDetail")
    public Result getApplyTypeDetail(HttpServletRequest httpServletRequest,@RequestParam("applyTypeCode") String applyTypeCode) {
        logger.info("Route==>ApplyTypeController method=>getApplyTypeDetail 根据应用类型编码查询应用类型详细数据，入参：{}", applyTypeCode);
        try {
            // todo  wjy  临时获取companyCode方法
            String companyCode = httpServletRequest.getHeader(Constants.COMPANY_CODE);
            companyCode = "000001";
            if (StringUtils.isEmpty(companyCode)) {
                logger.warn("Route=>ApplyTypeController method=>getApplyTypeDetail 根据应用类型编码查询应用类型详细数据，当前登录人归属租户信息异常");
                return Result.failWithMsg("登录人归属租户信息异常");
            }

            if (StringUtils.isNull(applyTypeCode)) {
                logger.info("根据应用类型编码查询应用类型详细数据失败{}", applyTypeCode);
                return Result.failWithMsg("应用类型编码不能为空");
            }
            //根据应用类型编码查询应用类型详细数据
            ApplyTypeDetailVo detailVo = applyTypeService.getApplyTypeDetail(applyTypeCode,companyCode);
            logger.info("Route==>ApplyTypeController method=getApplyTypeDetail 根据应用类型编码查询应用类型详细数据>>成功，出参：{}", JSON.toJSONString(detailVo));
            return new Result(Result.SUCCESS, "根据应用类型编码查询应用类型详细数据成功", detailVo);
        } catch (Exception e) {
            logger.error("Route==>ApplyTypeController method=>getApplyTypeDetail 根据应用类型编码查询应用类型详细数据异常，入参：{}，异常：{}", applyTypeCode, e);
            return handleException(e);
        }
    }

    /**
     * 修改应用类型数据
     * @param applyTypeAddDto
     * @return
     */
    @PostMapping("/updateApplyTypeInfo")
    public Result updateApplyTypeInfo(HttpServletRequest httpServletRequest,@RequestBody ApplyTypeAddDto applyTypeAddDto) {
        logger.info("Route==>ApplyTypeController method=updateApplyTypeInfo 修改应用类型数据，入参：{}", JSON.toJSONString(applyTypeAddDto));
        try {
            // todo  wjy  临时获取companyCode和userCode方法
            String companyCode = httpServletRequest.getHeader(Constants.COMPANY_CODE);
            //String userCode = httpServletRequest.getHeader(Constants.USER_CODE);
            String userName = httpServletRequest.getHeader(Constants.NAME);
            companyCode = "000001";
            //userCode = "001001";
            userName = "wjy";

            if (StringUtils.isEmpty(companyCode)) {
                logger.warn("Route=>ApplyTypeController method=>updateApplyTypeInfo 修改应用类型数据，当前登录人归属租户信息异常");
                return Result.failWithMsg("登录人归属租户信息异常");
            }
            /*if (StringUtils.isEmpty(userCode)) {
                logger.warn("Route=>ApplyTypeController method=>updateApplyTypeInfo 修改应用类型数据，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }*/
            if (StringUtils.isEmpty(userName)) {
                logger.warn("Route=>ApplyTypeController method=>updateApplyTypeInfo 修改应用类型数据，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }
            applyTypeAddDto.setCompanyCode(companyCode);
            applyTypeAddDto.setCreatePerson(userName);

            if (StringUtils.isNull(applyTypeAddDto.getApplyTypeCode())) {
                logger.info("修改应用类型数据失败{}", JSON.toJSONString(applyTypeAddDto));
                return Result.failWithMsg("应用类型编码为空");
            }
            if (StringUtils.isNull(applyTypeAddDto.getApplyTypeName())) {
                logger.info("修改应用类型数据失败{}", JSON.toJSONString(applyTypeAddDto));
                return Result.failWithMsg("应用类型名称为空");
            }else {
                //校验应用类型名称唯一
                //校验是否修改应用类型名称
                String applyTypeName = applyTypeService.getApplyTypeName(applyTypeAddDto.getApplyTypeCode(), companyCode);
                if (!applyTypeAddDto.getApplyTypeName().equals(applyTypeName)) {
                    int count = applyTypeService.verifyApplyTypeName(applyTypeAddDto.getApplyTypeName(), companyCode);
                    if (count > 0) {
                        logger.info("修改应用类型数据失败{}", JSON.toJSONString(applyTypeAddDto));
                        return Result.failWithMsg("应用类型名称不唯一");
                    }
                }
            }
            if (StringUtils.isNull(applyTypeAddDto.getApplyUrl())) {
                logger.info("修改应用类型数据失败{}", JSON.toJSONString(applyTypeAddDto));
                return Result.failWithMsg("应用类型前端链接为空");
            }
            if (StringUtils.isNull(applyTypeAddDto.getOrgType())) {
                logger.info("修改应用类型数据失败{}", JSON.toJSONString(applyTypeAddDto));
                return Result.failWithMsg("组织类型编码为空");
            }
            if (CollectionUtils.isEmpty(applyTypeAddDto.getOrgCodes())) {
                logger.info("修改应用类型数据失败{}", JSON.toJSONString(applyTypeAddDto));
                return Result.failWithMsg("组织编码为空");
            } else {
                //根据组织编码查询组织类型
                List<String> orgTypes = applyTypeService.verifyOrgType(applyTypeAddDto.getOrgCodes(),companyCode);
                if (CollectionUtils.isEmpty(orgTypes)) {
                    logger.info("修改应用类型数据失败{}", JSON.toJSONString(applyTypeAddDto));
                    return Result.failWithMsg("所选组织不是本系统组织类型下的组织");
                } else if (orgTypes.size() != 1) {//校验组织是否隶属于多个组织类型下的组织
                    logger.info("修改应用类型数据失败{}", JSON.toJSONString(applyTypeAddDto));
                    return Result.failWithMsg("所选组织隶属于多个组织类型下的组织");
                }
            }
            //校验关联应用
            if (CollectionUtils.isNotEmpty(applyTypeAddDto.getApplyCodes())) {
                //校验所关联的应用是否关联其他应用类型
                int flagSum = applyTypeService.verifyRelevancyApply(applyTypeAddDto.getApplyCodes(),applyTypeAddDto.getApplyTypeCode(), companyCode);
                if (flagSum != 0) {
                    logger.info("修改应用类型数据失败{}", JSON.toJSONString(applyTypeAddDto));
                    return Result.failWithMsg("关联应用系统已关联其他应用类型, 请重新选择 !");
                }
            }
            //修改应用类型数据
            applyTypeService.updateApplyTypeInfo(applyTypeAddDto);
            logger.info("Route==>ApplyTypeController method=updateApplyTypeInfo 修改应用类型数据>>成功，出参：{}", "");
            return Result.successWithMsg("修改应用类型数据成功");
        } catch (Exception e) {
            logger.error("Route==>ApplyTypeController method=>updateApplyTypeInfo 修改应用类型数据异常，入参：{}，异常：{}", JSON.toJSONString(applyTypeAddDto), e);
            return handleException(e);
        }
    }

    /**
     * 批量删除应用类型数据
     * @param applyTypeDeleteDto
     * @return
     */
    @PostMapping("/deleteApplyTypeInfo")
    public Result deleteApplyTypeInfo(HttpServletRequest httpServletRequest, @RequestBody ApplyTypeDeleteDto applyTypeDeleteDto) {
        logger.info("Route=>ApplyTypeController method=>deleteApplyTypeInfo 批量删除应用类型数据：{}", Json.toJsonString(applyTypeDeleteDto));
        try {
            // todo  wjy  临时获取companyCode和userCode方法
            String companyCode = httpServletRequest.getHeader(Constants.COMPANY_CODE);
            //String userCode = httpServletRequest.getHeader(Constants.USER_CODE);
            String userName = httpServletRequest.getHeader(Constants.NAME);
            companyCode = "000001";
            //userCode = "001001";
            userName = "wjy";

            if (StringUtils.isEmpty(companyCode)) {
                logger.warn("Route=>ApplyTypeController method=>deleteApplyTypeInfo 批量删除应用类型数据，当前登录人归属租户信息异常");
                return Result.failWithMsg("登录人归属租户信息异常");
            }
            /*if (StringUtils.isEmpty(userCode)) {
                logger.warn("Route=>ApplyTypeController method=>deleteApplyTypeInfo 批量删除应用类型数据，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }*/
            if (StringUtils.isEmpty(userName)) {
                logger.warn("Route=>ApplyTypeController method=>deleteApplyTypeInfo 批量删除应用类型数据，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }
            applyTypeDeleteDto.setCompanyCode(companyCode);
            applyTypeDeleteDto.setUpdatePerson(userName);

            if (org.springframework.util.CollectionUtils.isEmpty(applyTypeDeleteDto.getApplyTypeCodes())) {
                return new Result(Result.FAIL, "请选择数据再进行删除！");
            }
            //批量删除应用类型数据
            applyTypeService.deleteApplyTypeInfo(applyTypeDeleteDto);
            return new Result(Result.SUCCESS, "删除成功");
        } catch (Exception e) {
            logger.error("Route==>ApplyTypeController method=>deleteApplyTypeInfo 批量删除应用类型数据异常，入参：{}，异常：{}", Json.toJsonString(applyTypeDeleteDto), e);
            return handleException(e);
        }
    }

    /**
     * 功能描述：获取应用类型下拉列表
     * @return
     */
    @RequestMapping("/applyTypeList")
    public Result<List<String>> queryApplyTypeList(HttpServletRequest request) {
        try {
            String companyCode = "000001"/*request.getHeader(Constants.COMPANY_CODE)*/;
            if (StringUtils.isEmpty(companyCode)) {
                return Result.failWithMsg("当前登录信息异常");
            }
            return Result.success(applyTypeService.queryApplyTypeList(companyCode));
        } catch (Exception e) {
            logger.error("Route==>ApplyTypeController method=>queryApplyTypeList 获取应用类型数据异常：{}", e);
            return handleException(e);
        }
    }

}
